<template>
  <div class="utility-chart">
    <div v-if="loading" class="loading">数据加载中...</div>
    <div v-else ref="chartEl" style="width: 100%; height: 800px"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import * as echarts from "echarts";
import request from "@/utils/request";

// DOM元素引用和图表实例
const chartEl = ref(null);
let chartInstance = null;
const loading = ref(true);
const utilityData = ref({
  months: [],
  electricity: [],
  water: [],
});

// 从API获取水电费数据
const fetchUtilityData = async () => {
  try {
    const user = JSON.parse(sessionStorage.getItem("user"));
    if (!user?.username) {
      throw new Error("用户信息获取失败");
    }

    const res = await request.get(`/payhistory/findecharts/${user.username}`);

    if (res.code === "0" && res.data) {
      utilityData.value = {
        months: res.data.months,
        electricity: res.data.electricity,
        water: res.data.water,
      };
    }
  } catch (error) {
    console.error("获取水电费数据失败:", error);
    utilityData.value = {
      months: [],
      electricity: [],
      water: [],
    };
  } finally {
    loading.value = false;
  }
};

// 初始化图表
const initChart = () => {
  if (!chartEl.value || utilityData.value.months.length === 0) return;

  chartInstance = echarts.init(chartEl.value);

  // 保存原始数据用于恢复
  const originalData = {
    electricity: [...utilityData.value.electricity],
    water: [...utilityData.value.water],
  };

  const option = {
    title: {
      text: "每月水电费统计",
      left: "center",
      top: 30,
    },
    tooltip: {
      trigger: "axis",
      formatter: (params) => {
        const month = params[0].axisValue;
        // console.log("yue", month);
        const elec = params[0].data[1];
        // console.log("d", elec);
        const water = params[0].data[2];
        // console.log(water);
        let tooltipContent = `${month}<br/>`;

        // 检查电费数据是否存在（不为null/undefined/空字符串）
        if (elec !== null && elec !== undefined && elec !== "") {
          tooltipContent += `电费: ${elec}元<br/>`;
        }

        // 检查水费数据是否存在（不为null/undefined/空字符串）
        if (water !== null && water !== undefined && water !== "") {
          tooltipContent += `水费: ${water}元<br/>`;
        }

        // 如果都没有数据
        if (tooltipContent === `${month}<br/>`) {
          tooltipContent += "暂无数据";
        }

        return tooltipContent;
      },
    },
    legend: {
      data: ["电费", "水费"],
      top: 60,
    },
    dataset: {
      source: [
        ["月份", ...utilityData.value.months],
        ["电费", ...utilityData.value.electricity],
        ["水费", ...utilityData.value.water],
      ],
    },
    grid: [
      {
        top: "15%",
        height: "40%",
        left: "20%",
        right: "20%",
      },
      {
        top: "60%",
        height: "30%",
        left: "10%",
        right: "10%",
        containLabel: true,
      },
    ],
    xAxis: {
      type: "category",
      gridIndex: 0,
      axisLabel: {
        rotate: 30,
      },
    },
    yAxis: {
      type: "value",
      name: "费用（元）",
      gridIndex: 0,
    },
    series: [
      {
        type: "pie",
        id: "pie",
        radius: "30%",
        center: ["50%", "75%"],
        firstm: utilityData.value.months[0],

        label: {
          formatter: "{b}: {@03月}元 ({d}%)",
          position: "outside",
        },
        encode: {
          itemName: "月份",
          value: utilityData.value.months[0], // 默认显示第一个月数据
          tooltip: utilityData.value.months[0],
        },
        itemStyle: {
          borderRadius: 5,
          borderColor: "#fff",
          borderWidth: 2,
        },
      },
      {
        name: "电费",
        type: "line",
        smooth: true,
        seriesLayoutBy: "row",
        itemStyle: { color: "#5470C6" },
        xAxisIndex: 0,
        yAxisIndex: 0,
      },
      {
        name: "水费",
        type: "line",
        smooth: true,
        seriesLayoutBy: "row",
        itemStyle: { color: "#91CC75" },
        xAxisIndex: 0,
        yAxisIndex: 0,
      },
    ],
  };

  chartInstance.setOption(option);

  // 添加图例点击事件监听
  chartInstance.on("legendselectchanged", (params) => {
    const selected = params.selected;

    // 处理电费图例
    if ("电费" in selected) {
      if (selected["电费"]) {
        // 恢复电费数据
        utilityData.value.electricity = [...originalData.electricity];
      } else {
        // 清空电费数据
        utilityData.value.electricity = [];
      }
    }

    // 处理水费图例
    if ("水费" in selected) {
      if (selected["水费"]) {
        // 恢复水费数据
        utilityData.value.water = [...originalData.water];
      } else {
        // 清空水费数据
        utilityData.value.water = [];
      }
    }
    // 更新图表
    updateChart();
  });

  // 交互事件：鼠标移动时更新饼图数据
  chartInstance.on("updateAxisPointer", (event) => {
    const axisInfo = event.axesInfo[0];
    if (axisInfo) {
      const monthIndex = axisInfo.value;
      const month = utilityData.value.months[monthIndex];

      chartInstance.setOption({
        series: {
          id: "pie",
          label: {
            formatter: `{b}: {@${month}}元 ({d}%)`,
          },
          encode: {
            value: month,
            tooltip: month,
          },
        },
      });
    }
  });
};
// 新增更新图表函数
const updateChart = () => {
  if (!chartInstance) return;

  const option = {
    dataset: {
      source: [
        ["月份", ...utilityData.value.months],
        ["电费", ...utilityData.value.electricity],
        ["水费", ...utilityData.value.water],
      ],
    },
  };

  chartInstance.setOption(option);
};

// 响应式调整
const handleResize = () => {
  chartInstance?.resize();
};

onMounted(async () => {
  await fetchUtilityData();
  initChart();
  window.addEventListener("resize", handleResize);
});
// 修改onBeforeUnmount以移除事件监听
onBeforeUnmount(() => {
  window.removeEventListener("resize", handleResize);
  if (chartInstance) {
    chartInstance.off("legendselectchanged"); // 移除事件监听
    chartInstance.dispose();
  }
});
</script>

<style scoped>
.utility-chart {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  position: relative;
  min-height: 800px;
}

.loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 18px;
  color: #666;
}
</style>